"""
系统设置路由
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.blueprints.api import api_bp
from app.models.user import User
from app.models.log import SystemLog
from app.extensions import db
from datetime import datetime


# 系统配置存储（生产环境应使用数据库或配置文件）
SYSTEM_CONFIG = {
    'site_name': 'IT课程数据分析系统',
    'site_description': '基于Flask的数据驱动教学决策支持平台',
    'max_file_size': 16,  # MB
    'allowed_file_types': ['csv', 'xlsx', 'xls'],
    'session_timeout': 3600,  # 秒
    'enable_registration': True,
    'default_language': 'zh-CN',
    'items_per_page': 20,
    'enable_email_notifications': False,
    'smtp_host': '',
    'smtp_port': 587,
    'smtp_username': '',
    'smtp_use_tls': True,
    'enable_cache': False,
    'cache_timeout': 300,
    'enable_analytics': True,
    'maintenance_mode': False,
    'version': '1.0.0',
}


@api_bp.route('/settings/public', methods=['GET'])
def get_public_settings():
    """获取公开的系统设置（不需要认证）"""
    try:
        # 只返回公开的配置项
        public_config = {
            'site_name': SYSTEM_CONFIG.get('site_name', 'IT课程数据分析系统'),
            'site_description': SYSTEM_CONFIG.get('site_description', ''),
            'version': SYSTEM_CONFIG.get('version', '1.0.0'),
            'enable_registration': SYSTEM_CONFIG.get('enable_registration', True),
            'maintenance_mode': SYSTEM_CONFIG.get('maintenance_mode', False)
        }
        
        return jsonify({
            'success': True,
            'data': public_config
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/settings', methods=['GET'])
@jwt_required()
def get_settings():
    """获取系统设置（需要管理员权限）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 隐藏敏感信息
        safe_config = SYSTEM_CONFIG.copy()
        if 'smtp_password' in safe_config:
            safe_config['smtp_password'] = '******'
        
        return jsonify({
            'success': True,
            'data': safe_config
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/settings', methods=['PUT'])
@jwt_required()
def update_settings():
    """更新系统设置"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        data = request.get_json()
        
        # 更新配置
        for key, value in data.items():
            if key in SYSTEM_CONFIG:
                SYSTEM_CONFIG[key] = value
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='update',
            resource_type='system_settings',
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Updated system settings: {", ".join(data.keys())}'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Settings updated successfully',
            'data': SYSTEM_CONFIG
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/settings/reset', methods=['POST'])
@jwt_required()
def reset_settings():
    """重置系统设置为默认值"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 重置为默认值
        default_config = {
            'site_name': 'IT课程数据分析系统',
            'site_description': '基于Flask的数据驱动教学决策支持平台',
            'max_file_size': 16,
            'allowed_file_types': ['csv', 'xlsx', 'xls'],
            'session_timeout': 3600,
            'enable_registration': True,
            'default_language': 'zh-CN',
            'items_per_page': 20,
            'enable_email_notifications': False,
            'enable_cache': False,
            'cache_timeout': 300,
            'enable_analytics': True,
            'maintenance_mode': False,
        }
        
        SYSTEM_CONFIG.update(default_config)
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='reset',
            resource_type='system_settings',
            ip_address=request.remote_addr,
            status='success',
            level='WARNING',
            message='Reset system settings to default values'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Settings reset successfully',
            'data': SYSTEM_CONFIG
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/system/status', methods=['GET'])
@jwt_required()
def get_system_status():
    """获取系统状态"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        from app.models.course import Course
        from app.models.student_course import StudentCourse
        
        # 获取系统统计
        total_users = User.query.count()
        total_students = User.query.filter_by(role='student').count()
        total_teachers = User.query.filter_by(role='teacher').count()
        total_admins = User.query.filter_by(role='admin').count()
        total_courses = Course.query.count()
        total_enrollments = StudentCourse.query.count()
        total_logs = SystemLog.query.count()
        
        # 最近日志
        recent_logs = SystemLog.query.order_by(
            SystemLog.timestamp.desc()
        ).limit(10).all()
        
        import psutil
        import platform
        
        # 系统信息
        system_info = {
            'platform': platform.system(),
            'platform_version': platform.version(),
            'python_version': platform.python_version(),
            'cpu_percent': psutil.cpu_percent(interval=1),
            'memory_percent': psutil.virtual_memory().percent,
            'disk_percent': psutil.disk_usage('/').percent,
        }
        
        return jsonify({
            'success': True,
            'data': {
                'statistics': {
                    'total_users': total_users,
                    'total_students': total_students,
                    'total_teachers': total_teachers,
                    'total_admins': total_admins,
                    'total_courses': total_courses,
                    'total_enrollments': total_enrollments,
                    'total_logs': total_logs
                },
                'system_info': system_info,
                'recent_logs': [log.to_dict() for log in recent_logs],
                'config': SYSTEM_CONFIG
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': True,
            'data': {
                'statistics': {
                    'total_users': User.query.count(),
                    'total_students': User.query.filter_by(role='student').count(),
                    'total_teachers': User.query.filter_by(role='teacher').count(),
                    'total_courses': 0,
                },
                'system_info': {
                    'platform': 'Unknown',
                    'cpu_percent': 0,
                    'memory_percent': 0,
                },
                'config': SYSTEM_CONFIG
            }
        }), 200


@api_bp.route('/logs', methods=['GET'])
@jwt_required()
def get_system_logs():
    """获取系统日志"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        level = request.args.get('level')
        action = request.args.get('action')
        
        query = SystemLog.query
        
        if level:
            query = query.filter_by(level=level)
        if action:
            query = query.filter_by(action=action)
        
        pagination = query.order_by(
            SystemLog.timestamp.desc()
        ).paginate(page=page, per_page=per_page, error_out=False)
        
        logs = [log.to_dict() for log in pagination.items]
        
        return jsonify({
            'success': True,
            'data': logs,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/logs/clear', methods=['POST'])
@jwt_required()
def clear_logs():
    """清空系统日志"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 保留最近30天的日志
        from datetime import timedelta
        cutoff_date = datetime.utcnow() - timedelta(days=30)
        
        deleted_count = SystemLog.query.filter(
            SystemLog.timestamp < cutoff_date
        ).delete()
        
        # 记录清理操作
        log = SystemLog(
            user_id=current_user_id,
            action='clear_logs',
            resource_type='system_logs',
            ip_address=request.remote_addr,
            status='success',
            level='WARNING',
            message=f'Cleared {deleted_count} old log entries'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'Cleared {deleted_count} old log entries',
            'data': {
                'deleted_count': deleted_count
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/database/backup', methods=['POST'])
@jwt_required()
def backup_database():
    """数据库备份"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 这里应该实现实际的数据库备份逻辑
        # 示例：使用mysqldump或pg_dump
        
        backup_filename = f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql"
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='backup',
            resource_type='database',
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Database backup created: {backup_filename}'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Backup created successfully (功能演示)',
            'data': {
                'filename': backup_filename,
                'timestamp': datetime.now().isoformat()
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
